package net.zhuike.novel.app.ui.activity.anount;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;

import net.zhuike.novel.app.R;
import net.zhuike.novel.app.bean.BookChapterBean;
import net.zhuike.novel.app.service.UserService;
import net.zhuike.novel.app.ui.utils.AppUtils;
import net.zhuike.novel.app.ui.utils.SharedPreferencesUtil;
import net.zhuike.novel.app.ui.utils.SiteHelper;
import net.zhuike.novel.app.ui.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import framework.common.baseui.UeBaseActivity;

import framework.common.timer.TimeButton;
import framework.common.zanetwork.UeHttpUrl;
import framework.common.zanetwork.core.ResponseCallback;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by qi.wang on 2017/6/22.
 * 注册
 */

public class RegistActivity extends UeBaseActivity implements View.OnClickListener {
    private EditText reg_phone, reg_code, reg_pass, reg_pass_agin;
    private Context context;
    private Button sendReg;
    private ImageView showCode;
    private Button send_code_btn;
    private TextView clickCheck;
    String code = "";
    private int check = 1;
    private String phoneNumVal = "", codeVal = "", passwordVal = "", repeatPass = "", type = "4";
    private OkHttpClient mOkHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.activity_regist);
        context = this;
        hiddenFooter();
        showGoBackBtn();
        setTitleText("新用户注册");
        findBaseView(savedInstanceState);
    }

    public void findBaseView(Bundle savedInstanceState) {
        reg_phone = (EditText) findViewById(R.id.reg_phone);
        reg_code = (EditText) findViewById(R.id.reg_code);
        reg_pass = (EditText) findViewById(R.id.reg_pass);
        reg_pass_agin = (EditText) findViewById(R.id.reg_agin_pass);
        send_code_btn = (Button) findViewById(R.id.send_code_btn);
        showCode = (ImageView) findViewById(R.id.showCode);
        sendReg = (Button) findViewById(R.id.reg_button);
        clickCheck = (TextView) findViewById(R.id.check_agree);
        send_code_btn.setOnClickListener(this);
        sendReg.setOnClickListener(this);
        clickCheck.setOnClickListener(this);
        sendSms();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_code_btn:
                sendSms();
                break;
            case R.id.reg_button:
                if (reg_phone.getText().toString() == null || reg_phone.getText().toString().equals("")) {
                    ToastUtils.showSingleToast("请输入手机号/账号/邮箱");
                    return;
                } else if (reg_code.getText().toString() == null || reg_code.getText().toString().equals("")) {
                    ToastUtils.showSingleToast("请输入验证码");
                    return;
                } else if (reg_pass.getText().toString() == null || reg_pass.getText().toString().equals("")) {
                    ToastUtils.showSingleToast("请输入密码");
                    return;
                } else if (reg_pass_agin.getText().toString() == null || reg_pass_agin.getText().toString().equals("")) {
                    ToastUtils.showSingleToast("请再次输入密码");
                    return;
                } else if (!reg_pass_agin.getText().toString().equals(reg_pass.getText().toString())) {
                    ToastUtils.showSingleToast("两次密码不一致");
                    return;
                }else if(reg_pass.getText().toString().length()<6){
                    ToastUtils.showSingleToast("密码小于6位");
                    return;
                }
                phoneNumVal = reg_phone.getText().toString();
                codeVal = reg_code.getText().toString();
                passwordVal = reg_pass.getText().toString();
                repeatPass = reg_pass_agin.getText().toString();
                regist();
                break;
            case R.id.check_agree:
                if (check == 1) {
                    check = 0;
                    Drawable drawable = getResources().getDrawable(R.mipmap.select_no);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    clickCheck.setCompoundDrawables(drawable, null, null, null);
                } else {
                    check = 1;
                    Drawable drawable = getResources().getDrawable(R.mipmap.select_yes);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    clickCheck.setCompoundDrawables(drawable, null, null, null);
                }
                break;
        }
    }

    public void sendSms() {
        try {
            mOkHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)       //设置连接超时
                    .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
                    .writeTimeout(60, TimeUnit.SECONDS)          //设置写超时
                    .retryOnConnectionFailure(true)             //是否自动重连
                    .build();
            final Request request = new Request.Builder()
                    .url("http://47.91.148.42/code.jpg?t=" + System.currentTimeMillis())
                    .get()
                    .build();
            Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        String cookieList = response.headers().get("Set-Cookie");
                        String[] ck = cookieList.split(";");
                        String cookie[] = ck[0].split("=");
                        SharedPreferencesUtil.getInstance().putString("cookie", cookie[1]);
                        InputStream is = response.body().byteStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(is);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showCode.setImageBitmap(bitmap);
                            }
                        });

                        is.close();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
        }
    }

    public void regist() {
        try {
            String parmas =phoneNumVal+"?password="+AppUtils.EncoderByMd5(passwordVal)+"&password2="+AppUtils.EncoderByMd5(repeatPass)+"&email="+phoneNumVal+"&code="+codeVal;
            mOkHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)       //设置连接超时
                    .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
                    .writeTimeout(60, TimeUnit.SECONDS)          //设置写超时
                    .retryOnConnectionFailure(true)             //是否自动重连
                    .build();
            final Request request = new Request.Builder()
                    .url(UeHttpUrl.getResigt()+parmas)
                    .addHeader("User-Agent",
                            "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0")
                    .addHeader("Accept",
                            "text/html,application/xhtml+xml,application/xml;")
                    .addHeader("Accept-Language", "zh-cn")
                    .addHeader("Cache-Control", "no-cache")
                    .addHeader("Accept-Charset", "utf-8")
                    .addHeader("cookie",SharedPreferencesUtil.getInstance().getString("cookie"))
                    .get()
                    .build();
            Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        String str = response.body().string();
                        JSONObject obj = new JSONObject(str);
                        if (obj.getString("flag").equals("success")) {
                            setResult(RESULT_OK);
                            finish();
                        } else if (obj.getString("flag").equals("error")) {
                            if (obj.getString("data").equals("3")) {
                                Message message = new Message();
                                message.what = 1;
                                handlers.sendMessage(message);
                            } else {
                                Message message = new Message();
                                message.what = 2;
                                message.obj = obj.getString("data");
                                handlers.sendMessage(message);
                            }
                        }
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
        }
    }

    Handler handlers = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    ToastUtils.showToast("用户已存在");
                    break;
                case 2:
                    String msgs = (String) msg.obj;
                    try {
                        JSONObject obj = new JSONObject(msgs);
                        if(obj.has("code")) {
                            String code = obj.getString("code");
                            ToastUtils.showToast(code);
                        }else{
                            ToastUtils.showToast(msgs);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("注册");
        MobclickAgent.onResume(context);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("注册");
        MobclickAgent.onPause(context);
    }
}
